<?php

namespace App\Services\ApplyGoldRecordBatchExamine;

use App\Models\User;
use App\Models\GoldRecord;
use Brick\Math\RoundingMode;
use Illuminate\Support\Facades\Redis;
use App\Events\GoldRecordPaidEvent;
use Rainsens\Dinglog\Facades\Dinglog;
use Carbon\Carbon;

class ApplyGoldRecordExamine
{
	protected User $user;

	protected string $cacheId = '';

	public function __construct(User $user, $cacheId)
	{
		$this->user = $user;
		$this->cacheId = $cacheId;
	}

	public function apply()
	{
        $recordId = Redis::hGet($this->cacheId, 'gold_record_id');
       
        if ($recordId <= 0) return;
        
        if ($record = GoldRecord::find($recordId)) {
            //cashier('goldcoin')->payStorm($record);
            $record->update(['paid_at' => Carbon::now(), 'paid_method' => 'ptop']);
            $record->goldRecordVoucher()->update(['is_examine'=> true]);
            $resoldUser = User::lockForUpdate()->find($record->upGoldRecord->user_id);

            $profitPercent = big_decimal(cs('storm')->move_round_profit_percent);
            $profit = big_decimal($record->upGoldRecord->record_all_price)->multipliedBy($profitPercent->multipliedBy(0.02))
                ->toScale(2, RoundingMode::HALF_UP);

            $profit = $profit->plus($resoldUser->resold_profit);

            $resoldUser->update(['resold_profit'=>$profit]);

            Redis::hMset($this->cacheId, ['is_examine'=>true]);

            $this->user->addRecordToPendingCache($this->cacheId);
            $this->user->delRecordFromUnpaidCache($this->cacheId);
            event(new GoldRecordPaidEvent($record));
        }
    

	}
}
